package www.lzdodo.com.getwifi;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_scane) {
            new Thread(runnable).start();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    // 扫描WIFI列表
    private List<WIFIInfo> scaneWIFI() {
        WifiManager manager = (WifiManager)getSystemService(Context.WIFI_SERVICE);      // 获得系统wifi服务
        ArrayList<ScanResult> list = (ArrayList<ScanResult>)manager.getScanResults();   // 获取wifi列表
        List<WIFIInfo> wifilist = new ArrayList();
        long updatetime = System.currentTimeMillis() / 1000;

        for(ScanResult result : list) {
            WIFIInfo info = new WIFIInfo();
            info.ssid = result.SSID;
            info.bssid = result.BSSID;
            info.level = result.level;
            info.password = "";
            info.updatetime = updatetime;
            wifilist.add(info);
        }
        /*
        WIFIInfo info1 = new WIFIInfo();
        info1.ssid = "cisco-60A8";
        info1.bssid = "d8:24:bd:76:60:aa";
        wifilist.add(info1);

        WIFIInfo info2 = new WIFIInfo();
        info2.ssid = "Tenda_2E5560";
        info2.bssid = "c8:3a:35:2e:55:60";
        wifilist.add(info2);
        */
        findKEY(wifilist);
        return wifilist;
    }
    // 查询WIFI密码
    private void findKEY(List<WIFIInfo> wifilist) {
        // 10个一组用来计数的
        int count = 10;
        for (int i = 0; i < (int)(wifilist.size() / count); i++) {
            getKEY(wifilist, i * count, count);
        }
        int left = wifilist.size() % count;
        if (left != 0) {
            getKEY(wifilist, wifilist.size() - left, left);
        }
    }
    // 查询密码并保存起来
    private void getKEY(List<WIFIInfo> wifilist, int start, int len) {
        if (wifilist.size() == 0) return;
        if (start < 0 || start >= wifilist.size()) return;
        String ssids = "", bssids = "";
        for (int i = start; i < start + len && i < wifilist.size(); i++) {
            ssids = (ssids.length() == 0) ?  wifilist.get(i).ssid : ssids + ";" + wifilist.get(i).ssid;
            bssids = (bssids.length() == 0) ? wifilist.get(i).bssid : bssids + ";" + wifilist.get(i).bssid;
        }
        // 查询
        String url = String.format("http://webalive.sinaapp.com/wifi.php?ssid=%s&bssid=%s", ssids, bssids);
        try {
            String html = getURLResponse(url);
            int index = html.indexOf("<!--");
            if (index <= 0) return;
            String jsonstr = html.substring(0, index);
            try {
                JSONTokener json = new JSONTokener(jsonstr);
                JSONArray arr = (JSONArray)json.nextValue();
                for (int i = 0; i < arr.length(); i++) {
                    JSONObject item = arr.getJSONObject(i);
                    String ssid = item.getString("ssid");
                    String bssid = item.getString("bssid");
                    String password = item.getString("pwd");
                    // 将密码写回到列表中
                    for (int n = start; n < start + len && n < wifilist.size(); n++) {
                        if (wifilist.get(n).ssid.equalsIgnoreCase(ssid) &&
                            wifilist.get(n).bssid.equalsIgnoreCase(bssid)) {
                            wifilist.get(n).password = password;
                            break;
                        }
                    }
                }
            } catch (JSONException ex) {
                // 异常处理代码
                Log.e("JSON解析异常", ex.toString());
            }
        }
        catch (Exception e) { Log.e("@@@@@", url); e.printStackTrace(); }
    }
    // 获取指定URL的响应字符串
    private String getURLResponse(String urlString) {
        HttpURLConnection conn = null; //连接对象
        InputStream stream = null;
        String resultData = "";
        try {
            URL url = new URL(urlString);                   //URL对象
            conn = (HttpURLConnection)url.openConnection(); //使用URL打开一个链接
            //conn.setDoInput(true);                          //允许输入流，即允许下载
            //conn.setDoOutput(true);                         //允许输出流，即允许上传
            //conn.setUseCaches(false);                       //不使用缓冲
            //conn.setRequestMethod("GET");                   //使用get请求
            stream = conn.getInputStream();                //获取输入流，此时才真正建立链接
            InputStreamReader isr = new InputStreamReader(stream);
            BufferedReader bufferReader = new BufferedReader(isr);
            String inputLine  = "";
            while((inputLine = bufferReader.readLine()) != null){
                resultData += inputLine + "\n";
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(stream != null){
                try {
                    stream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(conn != null){ conn.disconnect(); }
        }
        return resultData;
    }
    // 在界面上显示wifi信号
    private void showWifis(List<WIFIInfo> wifis) {
        ListView listView = (ListView)findViewById(R.id.listView);
        WIFIInfoAdapter adapter = new WIFIInfoAdapter(this, wifis);
        listView.setAdapter(adapter);
    }
    // 适配器 参考http://blog.csdn.net/tianshuguang/article/details/7344315
    public class WIFIInfoAdapter extends BaseAdapter {
        private LayoutInflater _inflater = null;
        private List<WIFIInfo> wifis = null;
        private WIFIInfoAdapter(Context context, List<WIFIInfo> wifis) {
            // 根据context上下文加载布局，这里的是Demo17Activity本身，即this
            this._inflater = LayoutInflater.from(context);
            this.wifis = wifis;
        }
        @Override
        public int getCount() {
            // 在此适配器中所代表的数据集中的条目数
            return wifis.size();
        }
        @Override
        public Object getItem(int position) {
            // 获取数据集中与指定索引对应的数据项
            return wifis.get(position);
        }
        @Override
        public long getItemId(int position) {
            // 获取在列表中与指定索引对应的行id
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            // 如果缓存convertView为空，则需要创建View
            if(convertView == null) {
                holder = new ViewHolder();
                // 根据自定义的Item布局加载布局
                convertView = _inflater.inflate(R.layout.list_item, null);
                holder.img = (ImageView)convertView.findViewById(R.id.img);
                holder.ssid = (TextView)convertView.findViewById(R.id.ssid);
                holder.mac = (TextView)convertView.findViewById(R.id.mac);
                holder.info = (TextView)convertView.findViewById(R.id.info);
                // 将设置好的布局保存到缓存中，并将其设置在Tag里，以便后面方便取出Tag
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }

            String ssid = wifis.get(position).ssid;
            String mac = String.format("[ %s ]", wifis.get(position).bssid);
            String info = wifis.get(position).password.length() == 0 ? "未查到..." : wifis.get(position).password;
            int img;
            // 得到的值是一个0到-100的区间值，是一个int型数据，其中0到-50表示信号最好，-50到-70表示信号偏差，小于-70表示最差，有可能连接不上或者掉线。
            if (-100 > wifis.get(position).level) img = R.drawable.wifiico0;
            else if (-60 > wifis.get(position).level) img = R.drawable.wifiico1;
            else if (-50 > wifis.get(position).level) img = R.drawable.wifiico2;
            else img = R.drawable.wifiico3;

            holder.img.setBackgroundResource(img);
            holder.ssid.setText(ssid);
            holder.mac.setText(mac);
            holder.info.setText(info);
            return convertView;
        }
    }
    // ViewHolder静态类
    static class ViewHolder {
        public ImageView img;
        public TextView ssid;
        public TextView mac;
        public TextView info;
    }

    //
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            List<WIFIInfo> wifis = data.getParcelableArrayList("value");
            //Log.i("mylog","请求结果为-->" +  wifis.get(0).password);
            showWifis(wifis);
        }
    };
    // 子线程用来查询WIFI列表和请求数据
    Runnable runnable = new Runnable(){
        @Override
        public void run() {
            List<WIFIInfo> wifis = scaneWIFI();     // 子线程耗时工作, 网页查询数据

            Message msg = new Message();
            Bundle data = new Bundle();
            data.putParcelableArrayList("value", (ArrayList<WIFIInfo>) wifis);
            msg.setData(data);
            handler.sendMessage(msg);
        }
    };


}

// WIFI信息类
class WIFIInfo implements Parcelable {
    public String ssid = "";        // 信号SSID
    public String bssid = "";       // 信号BSSID
    public String password = "";    // 密码
    public int level = 0;           // 信号强度
    public long updatetime = 0;     // 更新时间
    public double longitude = 0;    // 经度
    public double latitude = 0;     // 纬度
    @Override
    public int describeContents() {
        return 0;
    }
    @Override
    public void writeToParcel(Parcel dest, int flags) {
    }

}
